import json
import time

from modules.task.baidu import get_baidu_data
from modules.task.q360 import get_q360_data
from modules.task.weibo import get_weibo_data
from modules.threadpool.threadpool import ThreadPool
from modules.utils.configs import get_configs
from modules.utils.log_util import LOGGER
from modules.utils.redis_cache import CACHE


def task_running():
    def q360_data_task():
        try:
            q360_data = get_q360_data()
            if q360_data:
                CACHE.set("q360_data", json.dumps(q360_data).encode("utf-8"))
        except Exception as e:
            LOGGER.log("线程执行 q360_data_task 获取数据时异常")
            LOGGER.log(e)

    def weibo_data_task():
        try:
            weibo_data = get_weibo_data()
            if weibo_data:
                CACHE.set("weibo_data", json.dumps(weibo_data).encode("utf-8"))
        except Exception as e:
            LOGGER.log("线程执行 weibo_data_task 获取数据时异常")
            LOGGER.log(e)

    def baidu_data_task():
        try:
            baidu_data = get_baidu_data()
            if baidu_data:
                CACHE.set("baidu_data", json.dumps(baidu_data).encode("utf-8"))
        except Exception as e:
            LOGGER.log("线程执行 weibo_data_task 获取数据时异常")
            LOGGER.log(e)

    # 开启线程执行
    LOGGER.info("开启线程执行抓取任务")
    ThreadPool.get_instance().submit(q360_data_task)
    ThreadPool.get_instance().submit(weibo_data_task)
    ThreadPool.get_instance().submit(baidu_data_task)


def start_check():
    def interval():
        while True:
            taskStop = CACHE.get("taskStop")
            while not taskStop:
                task_running()
                config = get_configs().get("default")
                interval_time = config.get("interval")
                time.sleep(interval_time)
                taskStop = CACHE.get("taskStop")
    ThreadPool.get_instance().submit(interval)
